package models

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"gorm.io/gorm"
)

// AgentRelation 代理商关系表
type AgentRelation struct {
	Model
	AgentID     int    `json:"agent_id"  gorm:"unique;comment:'代理商ID'"`
	SuperiorID  int    `json:"superior_id" gorm:"comment:'上级代理ID'"`
	BaseAgentId int    `json:"base_agent_id" gorm:"comment:'所属代理商id'"`
	Relation    string `json:"relation" gorm:"comment:'代理关系 逗号隔开'"`
}

// AgentRelationGetInfoByAgentNo 通过id获取详情
func AgentRelationGetInfoByAgentNo(agentId interface{}) (map[string]string, error) {
	agentRelation := new(AgentRelation)
	err := db.Model(&AgentRelation{}).Where("agent_id = ?", agentId).Scan(&agentRelation).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		logrus.WithError(err).Error("代理关系不存在: agentNo:%d err:%v", agentId, err)
		return nil, fmt.Errorf("代理关系不存在")
	}
	if agentRelation.ID == 0 {
		logrus.WithError(err).Errorf("代理关系不存在 agent_no: %s", agentId)
		return nil, errors.New("代理关系不存在")
	}

	return map[string]string{
		"agentId":      cast.ToString(agentRelation.AgentID),
		"superiorId":   cast.ToString(agentRelation.SuperiorID),
		"baseAgentUid": cast.ToString(agentRelation.BaseAgentId),
		"relation":     agentRelation.Relation,
	}, nil
}

// AgentRelationAdd 添加
func AgentRelationAdd(agentId, superiorId interface{}, relation string, baseAgentId int) error {
	if baseAgentId == 0 {
		baseAgentId = cast.ToInt(agentId)
	}
	agentRelation := &AgentRelation{
		AgentID:     cast.ToInt(agentId),
		SuperiorID:  cast.ToInt(superiorId),
		BaseAgentId: baseAgentId,
		Relation:    relation,
	}
	err := db.Create(agentRelation).Error

	if err != nil {
		logrus.WithError(err).Infof("代理商关系添加失败: agentId:%s superiorId:%s relation:%s baseAgentId:%d", agentId, superiorId, relation, baseAgentId)
		return fmt.Errorf("代理商关系添加失败")
	}

	return nil
}
